import time
import urllib2
from msgpack import packb, unpackb
from httplib import HTTPConnection

FILE_NAME=r'/Users/monstar-216/Downloads/%s.txt'

BOUNDARY = '----------%s' % hex(int(time.time() * 1000))

HTTP_URL = r'http://192.168.10.237/special_stage/place/1/time/3'

HTTP_HEADER = {
               'Content-Type': 'multipart/form-data; boundary=%s' % BOUNDARY,
               'User-Agent': 'Mozilla/5.0',
               }

def getHttpRequestResponse(http_url, header, http_body):
    req=urllib2.Request(http_url, data=http_body)
    
    for key in HTTP_HEADER:
        req.add_header(key, HTTP_HEADER[key])
    
    resp = urllib2.urlopen(req, timeout=5)
    return resp.read()

def getHttpRequestResponse2(host, method, url, body, headers):
    connect = HTTPConnection(host, timeout=5)
    connect.request(method, url, body, headers)
    return connect.getresponse()
    
    
def createBody(filename):
    with open(filename, 'rb') as f:
        content = f.read()
    
    data = []
    data.append('--%s' % BOUNDARY)
    '''
    data.append('Content-Disposition: form-data; name="%s"\r\n' % 'username')
    data.append('jack')
    data.append('--%s' % BOUNDARY)
    
    data.append('Content-Disposition: form-data; name="%s"\r\n' % 'mobile')
    data.append('13800138000')
    data.append('--%s' % BOUNDARY)
    '''
    data.append('Content-Disposition: form-data; name="%s"; filename="data.txt"' % 'data')
    data.append('Content-Type: %s\r\n' % 'multipart/form-data;')
    data.append(content)
    data.append('--%s--\r\n' % BOUNDARY)
    
    return '\r\n'.join(data)

def messagePack2File():
    msgp = packb(INPUT_DATA)
    filename = FILE_NAME%INPUT_DATA['user_id']
    with open(filename, "wb") as f:
        f.write(msgp)

INPUT_DATA = {'vcheck': 0, 'user_id': 209117509, '_os': 'i', 'd_ver': '', 'token': '149557', 'version': '', 'app_ver': '2.4.4.1'}

if __name__ == '__main__':
    messagePack2File()
    response = getHttpRequestResponse2('192.168.10.237', 'PUT', '/gacha/ticket_buy', createBody(FILE_NAME%INPUT_DATA['user_id']), HTTP_HEADER)
    if response.status == 200:
        unres = unpackb(response.read())
        import json
        print json.dumps(unres, ensure_ascii=False, indent=2)
    else:
        print response.status,response.reason
    
    
    
    
